<template>
  <div class="container" style="height: auto">
    <el-form>
      <el-form-item>
        <div class="upload">
          <div>
            <input type="file" id="fileUpload" @change="fileChange($event)">
            <label class="status">上传状态: <span>{{statusText}}</span></label>
          </div>
          <div class="upload-type" style="width: auto">
<!--            上传方式一, 使用 UploadAuth 上传:-->
            <button @click="authUpload" :disabled="uploadDisabled">开始上传</button>
            <button @click="pauseUpload" :disabled="pauseDisabled">暂停</button>
            <button :disabled="resumeDisabled" @click="resumeUpload">恢复上传</button>
            <el-progress style="width:480px"  :text-inside="true" :stroke-width="24" :percentage="authProgress" status="success"></el-progress>
            <p v-if="fileName" >{{ fileName }}</p>
            <!--        <span class="progress">上传进度: <i id="auth-progress">{{authProgress}}</i> %</span>-->
          </div>
        </div>
        <div>

        </div>
      </el-form-item>

    </el-form>
<!--    <div class="info">uploadAuth及uploadAddress参数请查看<a href="https://help.aliyun.com/document_detail/55407.html" target="_blank">获取上传地址和凭证</a></div>-->
  </div>
</template>
<script>
  import axios from 'axios'
  import {getVodParam, refreshVodParam} from "@/api/modules/vodApi";

  export default {
    props:{
      value:{
        type:String,
      }
    },
    emits:['getVideoId'],
    data () {
      return {
        timeout: '',
        partSize: '',
        parallel: '',
        retryCount: '',
        retryDuration: '',
        region: 'cn-shanghai',
        userId: '1303984639806000',
        file: null,
        fileName:'',
        authProgress: 0,
        uploadDisabled: true,
        resumeDisabled: true,
        pauseDisabled: true,
        uploader: null,
        statusText: '',
      }
    },
    methods: {

      onSuccess(){
        this.$emit()
      },


      fileChange (e) {
        this.file = e.target.files[0]
        if (!this.file) {
          alert("请先选择需要上传的文件!")
          return
        }
        var Title = this.file.name
        var userData = '{"Vod":{}}'
        if (this.uploader) {
          this.uploader.stopUpload()
          this.authProgress = 0
          this.statusText = ""
        }
        this.uploader = this.createUploader()
        console.log(userData)
        this.uploader.addFile(this.file, null, null, null, userData)
        console.log(this.uploader)
        this.uploadDisabled = false
        this.pauseDisabled = true
        this.resumeDisabled = true
      },
      authUpload () {
        // 然后调用 startUpload 方法, 开始上传
        if (this.uploader !== null) {
          this.uploader.startUpload()
          this.uploadDisabled = true
          this.pauseDisabled = false
        }
      },
      // 暂停上传
      pauseUpload () {
        if (this.uploader !== null) {
          this.uploader.stopUpload()
          this.resumeDisabled = false
          this.pauseDisabled = true
        }
      },
      // 恢复上传
      resumeUpload () {
        if (this.uploader !== null) {
          this.uploader.startUpload()
          this.resumeDisabled = true
          this.pauseDisabled = false
        }
      },
      createUploader (type) {
        let self = this
        let uploader = new AliyunUpload.Vod({
          timeout: self.timeout || 60000,
          partSize: Math.round(self.partSize || 1048576),
          parallel: self.parallel || 5,
          retryCount: self.retryCount || 3,
          retryDuration: self.retryDuration || 2,
          region: self.region,
          userId: self.userId,
          localCheckpoint: true, //此参数是禁用服务端缓存，不影响断点续传
          // 添加文件成功
          addFileSuccess: function (uploadInfo) {
            self.uploadDisabled = false
            self.resumeDisabled = false
            self.statusText = '添加文件成功, 等待上传...'
            console.log("addFileSuccess: " + uploadInfo.file.name )
            // console.log( uploadInfo )
          },
          // 开始上传
          onUploadstarted: function (uploadInfo) {
            console.log(uploadInfo)
            if (!uploadInfo.videoId) {
              getVodParam({fileName:uploadInfo.file.name,title:uploadInfo.file.name}).then( res =>{
                console.log(res)
                let uploadAuth = res.data.uploadAuth
                let uploadAddress = res.data.uploadAddress
                self.videoId = res.data.videoId
                uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress,self.videoId)
              })
              self.statusText = '文件开始上传...'
              console.log("onUploadStarted:" + uploadInfo.file.name + ", endpoint:" + uploadInfo.endpoint + ", bucket:" + uploadInfo.bucket + ", object:" + uploadInfo.object)
            } else {
              refreshVodParam({videoId:uploadInfo.videoId}).then( res=>{
                      let uploadAddress = res.data.uploadAddress
                      let uploadAuth = res.data.uploadAuth
                      self.videoId = res.data.videoId
                  uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress,self.videoId)
                  }
              )
            }
          },
          // 文件上传成功
          onUploadSucceed: function (uploadInfo) {
            console.log("onUploadSucceed: " + uploadInfo.file.name + ", endpoint:" + uploadInfo.endpoint + ", bucket:" + uploadInfo.bucket + ", object:" + uploadInfo.object)
            self.fileName = uploadInfo.file.name
            self.$emit('getVideoId',self.videoId)
            self.$emit('showVideo',uploadInfo.file.name)
            self.statusText = '文件上传成功!'
          },
          // 文件上传失败
          onUploadFailed: function (uploadInfo, code, message) {
            console.log("onUploadFailed: file:" + uploadInfo.file.name + ",code:" + code + ", message:" + message)
            self.statusText = '文件上传失败!'
          },
          // 取消文件上传
          onUploadCanceled: function (uploadInfo, code, message) {
            console.log("Canceled file: " + uploadInfo.file.name + ", code: " + code + ", message:" + message)
            self.statusText = '文件已暂停上传'
          },
          // 文件上传进度，单位：字节, 可以在这个函数中拿到上传进度并显示在页面上
          onUploadProgress: function (uploadInfo, totalSize, progress) {
            console.log("onUploadProgress:file:" + uploadInfo.file.name + ", fileSize:" + totalSize + ", percent:" + Math.ceil(progress * 100) + "%")
            let progressPercent = Math.ceil(progress * 100)
            self.authProgress = progressPercent
            self.statusText = '文件上传中...'
          },
          // 上传凭证超时
          onUploadTokenExpired: function (uploadInfo) {
            // 上传大文件超时, 如果是上传方式一即根据 UploadAuth 上传时
            // 需要根据 uploadInfo.videoId 调用刷新视频上传凭证接口(https://help.aliyun.com/document_detail/55408.html)重新获取 UploadAuth
            // 然后调用 resumeUploadWithAuth 方法, 这里是测试接口, 所以我直接获取了 UploadAuth
            let refreshUrl = 'https://demo-vod.cn-shanghai.aliyuncs.com/voddemo/RefreshUploadVideo?BusinessType=vodai&TerminalType=pc&DeviceModel=iPhone9,2&UUID=59ECA-4193-4695-94DD-7E1247288&AppVersion=1.0.0&Title=haha1&FileName=xxx.mp4&VideoId=' + uploadInfo.videoId
            axios.get(refreshUrl).then(({data}) => {
              let uploadAuth = data.UploadAuth
              uploader.resumeUploadWithAuth(uploadAuth)
              console.log('upload expired and resume upload with uploadauth ' + uploadAuth)
            })
            self.statusText = '文件超时...'
          },
          // 全部文件上传结束
          onUploadEnd: function (uploadInfo) {
            console.log("onUploadEnd: uploaded all the files")
            self.statusText = '文件上传完毕'
          }
        })
        return uploader
      }
    }
  }
</script>
